#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:loginResource.py
# author:熊泓钦
# datetime:2024/3/19 8:52
# software: PyCharm

"""
this is function  description 
"""

from flask import jsonify
from flask_restful import Resource, reqparse
from werkzeug.exceptions import BadRequest

from service.administratorService import AdministratorService
from service.teacherService import TeacherService
from utils.response_code import RET, error_map_EN
from utils.loggings import logger
from utils.jwt import MakeToken
from utils.responseParser import ResponseParser
from utils.rsa_encryption_decryption import RSAEncryptionDecryption
from service.studentService import StudentService


# 超管登录
class AdminLoginResource(Resource):
    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument("administrator_id", type=int, location='form', required=True, help="administrator_id参数类型不正确或缺失")
        parser.add_argument("password", type=str, location="form", required=True, help="password参数类型不正确或缺失")
        try:
            global res
            data = parser.parse_args()
            kwargs = {
                "administrator_id": data.get("administrator_id"),
            }
            res = AdministratorService.get(**kwargs)
            if res.get('data')[0]['avatar'] is not None:
                res.get('data')[0]['avatar'] = res.get('data')[0]['avatar'].decode()
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify(ResponseParser.parse_res(**res))
            user = res.get("data")
            cipher = user[0].get('password')
            plain = RSAEncryptionDecryption.decrypt(cipher_text=cipher)
            if plain == data.get("password"):
                logger.info('login success')
                id = user[0].get("administrator_id")
                return jsonify({
                    "code": RET.OK,
                    "message": "登录成功",
                    "data": {
                        "user": user[0],
                        "token": MakeToken(UserID=id, UserType='administrator'),
                    }
                })
            else:
                logger.error('log in failed')
                return jsonify({
                    "code": RET.PWDERR,
                    "error": error_map_EN[RET.PWDERR],
                    "message": "登录失败",
                })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))
        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 学生登录
class StuLoginResource(Resource):
    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument("student_id", type=int, location='form', required=True, help="student_id参数类型不正确或缺失")
        parser.add_argument("password", type=str, location="form", required=True, help="password参数类型不正确或缺失")
        try:
            global res
            data = parser.parse_args()
            kwargs = {
                "student_id": data.get("student_id"),
            }
            res = StudentService.get(**kwargs)
            if res.get('data')[0]['avatar'] is not None:
                res.get('data')[0]['avatar'] = res.get('data')[0]['avatar'].decode()
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify(ResponseParser.parse_res(**res))
            user = res.get("data")
            cipher = user[0].get('password')
            plain = RSAEncryptionDecryption.decrypt(cipher_text=cipher)
            if plain == data.get("password"):
                logger.info('login success')
                id = user[0].get("student_id")
                return jsonify({
                    "code": RET.OK,
                    "message": "登录成功",
                    "data": {
                        "user": user[0],
                        "token": MakeToken(UserID=id, UserType='student'),
                    }
                })
            else:
                logger.error('log in failed')
                return jsonify({
                    "code": RET.PWDERR,
                    "error": error_map_EN[RET.PWDERR],
                    "message": "登录失败",
                })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))
        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 教师登录
class TeacherLoginResource(Resource):
    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument("teacher_id", type=int, location='form', required=True, help="teacher_id参数类型不正确或缺失")
        parser.add_argument("password", type=str, location="form", required=True, help="password参数类型不正确或缺失")
        try:
            global res
            data = parser.parse_args()
            kwargs = {
                "teacher_id": data.get("teacher_id"),
            }
            res = TeacherService.get(**kwargs)
            if res.get('data')[0]['avatar'] is not None:
                res.get('data')[0]['avatar'] = res.get('data')[0]['avatar'].decode()
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify(ResponseParser.parse_res(**res))
            user = res.get("data")
            cipher = user[0].get('password')
            plain = RSAEncryptionDecryption.decrypt(cipher_text=cipher)
            if plain == data.get("password"):
                logger.info('login success')
                id = user[0].get("teacher_id")
                return jsonify({
                    "code": RET.OK,
                    "message": "登录成功",
                    "data": {
                        "user": user[0],
                        "token": MakeToken(UserID=id, UserType='teacher'),
                    }
                })
            else:
                logger.error('log in failed')
                return jsonify({
                    "code": RET.PWDERR,
                    "error": error_map_EN[RET.PWDERR],
                    "message": "登录失败",
                })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))
        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))
